from langchain_ollama.llms import OllamaLLM
from langchain.prompts import PromptTemplate
from langchain.agents import create_react_agent
from langchain import hub
from langchain.agents import AgentExecutor
from langchain.tools import Tool
import yaml
from tools.searchBySerpapi import get_UID
from langchain_openai import ChatOpenAI

def related_agent(input:str):
    with open('config.yaml', 'r') as file:
        data = yaml.safe_load(file)
    llm = OllamaLLM(model="qwen:72b")

    template = """given the {input} I want you to get a related 微博 UID.
                Your answer should contain only a UID.
                The URL always starts with https://weibo.com/u/
                for example, if https://weibo.com/u/1669879400 is her 微博, then 1669879400 is her UID
                This is only the example don't give me this, but the actual UID

                You have access to the following tools:

                {tools}

                Use the following format:

                Question: the input question you must answer
                Thought: you should always think about what to do
                Action: the action to take, should be one of [{tool_names}]
                Action Input: the input to the action
                Observation: the result of the action
                ... (this Thought/Action/Action Input/Observation can repeat N times)
                Thought: I now know the final answer
                Final Answer: the final answer to the original input question

                Begin!

                Question: {input}
                Thought:{agent_scratchpad}
                """

    prompt = PromptTemplate.from_template(template)


    tools = [
        Tool(
            name="get_info",
            func=get_UID,
            description="you must use this tool to get the info"
        )
    ]

    openai = ChatOpenAI(model="gpt-3.5-turbo",
                        temperature=0,
                        max_tokens=2000,
                        api_key=data['openai_api_key_github_website'],
                        base_url=data['openai_github_website_base_url'])

    agent = create_react_agent(
        openai,
        tools,
        prompt,
        )

    agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True,handle_parsing_errors=True)
    print("第一次运行的结果：")
    result=agent_executor.invoke({"input": f'{input}'})

    return result
